package com.bigmodel.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

public class FtlUtil {

    private static Configuration configuration = null;

    /**
     * 创建configuration
     * @param ftlSrc  模版存放路径,ftl所在的文件夹路径
     */
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setClassForTemplateLoading(FtlUtil.class, "/freemarker");
            configuration.setTemplateLoader(new ClassTemplateLoader(FtlUtil.class,"/freemarker"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String generateContent(Map<String, Object> dataMap, String ftlName) {
        Template t = null;
        Writer out = new StringWriter();
        try {
            t = configuration.getTemplate(ftlName);
            //生成
            t.process(dataMap, out);
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
